<script>
export default {
  name: "SelectPlatformSiteShop"
}
</script>

<script setup>
import {nextTick, reactive} from 'vue'
import api from './api'
import {cloneDeep} from 'lodash'

const optionsConfig = {
  filterable: true,
  collapseTags: true,
  collapseTagsTooltip: true,
  clearable: true,
  maxCollapseTags: 1,
}

const props = defineProps({
  multiple: {
    type: Boolean,
    default: false,
  },
  // 验证
  required: {
    type: Boolean,
    default: false,
  },
  // 行内表单
  inline: {
    type: Boolean,
    default: true,
  },
  labelWidth: {
    type: String,
    default: '120px',
  },
  showLabel: {
    type: Boolean,
    default: false,
  },
  platformMultiple: {
    type: Number,
    default: 0,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  platform: {
    type: [String, Number, Array],
    default: () => []
  },
  site: {
    type: [Array],
    default: () => []
  },
  shop: {
    type: Array,
    default: () => []
  },
  showRule: {
    type: Array,
    default: () => ([true, true, true])
  },
  checkShop: {
    type: Boolean,
    default: true,
  },
})

const optionsData = reactive({
  platform: [],
  sites: [],
  shop: [],
})

const platformCurrent = computed({
  get: () => {
    return props.platform
  },
  set: value => {
    emit('update:platform', value)
  }
})

const siteCurrent = computed({
  get: () => {
    return props.site
  },
  set: value => {
    emit('update:site', value)
  }
})

const shopCurrent = computed({
  get: () => {
    return props.shop
  },
  set: value => {
    emit('update:shop', value)
  }
})

const emit = defineEmits(['update:platform', 'update:sites', 'update:shop'])

const handleChange = (type, value) => {
  switch (type) {
    case 'platform':
      // initSiteList(value)
      // optionsData.sites = []
      // siteCurrent.value = props.multiple ? [] : ''
      // optionsData.shop = []
      // shopCurrent.value = props.multiple ? [] : ''
      optionsData.sites = []
      siteCurrent.value = props.multiple ? [] : ''
      optionsData.shop = []
      shopCurrent.value = props.multiple ? [] : ''
      break;
    case 'site':
      initShopList(value)
      optionsData.shop = []
      shopCurrent.value = props.multiple ? [] : ''
      break;
    case 'shop':
      break;
  }
  emit('input', {
    platform_id: platformCurrent,
    site_id: siteCurrent,
    shop_id: shopCurrent,
  })
}

const initSiteList = async (value) => {
  const res = await api.apiGetSiteList({
    platform_ids: Array.isArray(value) ? value : [value]
  })
  optionsData.sites = res.data
}

watch(() => platformCurrent.value, value => {
  initSiteList(value)
  // 暂用于回显
  if(siteCurrent.value.length){
    nextTick(()=>{
      initShopList(siteCurrent.value)
    })
    
  }
}, {deep: true, immediate: true})

const initPlatFormList = async () => {
  const res = await api.apiGetPlatFormList()
  optionsData.platform = res.data
}

const initShopList = async (value) => {
  const res = await api.apiGetShopList({
    site_ids: Array.isArray(value) ? value : [value],
    platform_ids: Array.isArray(props.platform) ? props.platform : [props.platform]
  })
  optionsData.shop = res.data
}

onMounted(() => {
  initPlatFormList()

  // 获取全部店铺   待优化  初始化两种操作 1.可先选择店铺   2.选择完站点才可选择店铺
  if(props.checkShop){
    api.apiGetShopList({site_ids: [],platform_ids: []}).then(res=>{
      optionsData.shop = res.data
    })
  }


})

const platformMultipleCur = computed(() => {
  if (props.platformMultiple === 1) return false
  return props.multiple
})

const checkAll = (key, type) => {
  switch (key) {
    case 'platform':
      platformCurrent.value = type === 'checkAll' ? optionsData.platform.map(v => v.platform_id) : optionsData.platform.filter(v => !platformCurrent.value.includes(v.platform_id)).map(v => v.platform_id)
      break;
    case 'site':
      siteCurrent.value = type === 'checkAll' ? optionsData.sites.map(v => v.site_id) : optionsData.sites.filter(v => !siteCurrent.value.includes(v.site_id)).map(v => v.site_id)
      break;
    case 'shop':
      shopCurrent.value = type === 'checkAll' ? optionsData.shop.map(v => v.shop_id) : optionsData.sites.filter(v => !shopCurrent.value.includes(v.shop_id)).map(v => v.shop_id)
      break;
    default:
      break;
  }
}

defineExpose({
  /**
   * 选中的源数据，主要用于一些特殊场景：后端用label值去查询，避免多表查询影响查询效率，极致优化~ 🐎 🗑️
   * @returns {{site: [], shop: [], platform: []}}
   */
  getSelectedData: () => {
    let pf = cloneDeep(platformCurrent.value)
    let sc = cloneDeep(siteCurrent.value)
    let sp = cloneDeep(shopCurrent.value)
    pf = Array.isArray(pf) ? pf : (pf ? [pf] : [])
    sc = Array.isArray(sc) ? sc : (sc ? [sc] : [])
    sp = Array.isArray(sp) ? sp : (sp ? [sp] : [])
    const res = {
      platform: [],
      site: [],
      shop: [],
    }
    res.platform = pf.map(item => item && optionsData.platform.find(v => v.platform_id === item))
    res.site = sc.map(item => item && optionsData.sites.find(v => v.site_id === item))
    res.shop = sp.map(item => item && optionsData.shop.find(v => v.shop_id === item))
    return res
  },
  checkAll
})


</script>

<template>
  <div :class="`select-platform-site-shop ${inline ? 'inline' : ''}`">
    <div v-show="showRule[0]" class="sel-platform-site-shop-item">
      <label class="el-form-item__label" v-show="showLabel" :style="{'width': labelWidth}">
        <span class="required" v-if="required">* </span>平台：
      </label>
      <el-select v-bind="optionsConfig"
                 v-model="platformCurrent"
                 :multiple="platformMultipleCur"
                 placeholder="平台"
                 style="width: 180px"
                 :disabled="disabled"
                 @change="handleChange('platform', $event)">
        <el-option
            v-for="item in optionsData.platform"
            :key="item.platform_id"
            :label="item.platform_name"
            :value="item.platform_id"
        />
      </el-select>
    </div>

    <div v-show="showRule[1]" class="sel-platform-site-shop-item">
      <label class="el-form-item__label" v-show="showLabel" :style="{'width': labelWidth}">
        <span class="required" v-if="required">* </span>站点：
      </label>
      <el-select v-bind="optionsConfig"
                 v-model="siteCurrent"
                 :multiple="multiple"
                 placeholder="站点"
                 style="width: 200px"
                 v-show="showRule[1]"
                 :disabled="disabled"
                 @change="handleChange('site', $event)">
        <el-option
            v-for="item in optionsData.sites"
            :key="item.site_id"
            :label="item.site_abbrev"
            :value="item.site_id"
        />
      </el-select>
    </div>

    <div v-show="showRule[2]" class="sel-platform-site-shop-item">
      <label class="el-form-item__label" v-show="showLabel" :style="{'width': labelWidth}">
        <span class="required" v-if="required">* </span>店铺：
      </label>
      <el-select v-bind="optionsConfig"
                 v-model="shopCurrent"
                 :multiple="multiple"
                 placeholder="店铺"
                 style="width: 280px"
                 :disabled="disabled"
                 @change="handleChange('shop', $event)">
        <el-option
            v-for="item in optionsData.shop"
            :key="item.shop_id"
            :label="item.shop_name"
            :value="item.shop_id"
        />
      </el-select>
    </div>
  </div>
</template>

<style scoped lang="scss">
.select-platform-site-shop.inline {
  .sel-platform-site-shop-item {
    display: inline-block;
  }
}
.el-form-item__label{
  font-weight: 500;
  color: var(--base-text-color);
}

.select-platform-site-shop {
  .sel-platform-site-shop-item {
    //margin-bottom: 18px;
    //display: flex;
    //.el-select {
    //  flex: 1;
    //}
  }

  .required {
    color: #f56c6c;
    font-size: 16px;
    font-weight: bold;
  }
}
</style>